package com.brotherly.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileHelper
{

    public static void copyFile(InputStream in, OutputStream out) throws IOException
    {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
    }

    public static String readFile(InputStream in)
    {
        try
        {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, read);
            }
            byte[] bytes = out.toByteArray();
            String content = new String(bytes, "utf-8");
            return content;
        }
        catch (Exception e)
        {}
        return null;
    }

    public static byte[] readFileBytes(String path)
    {
        FileInputStream in = null;
        try
        {
            in = new FileInputStream(path);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, read);
            }
            byte[] bytes = out.toByteArray();
            return bytes;

        }
        catch (Exception e)
        {}
        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String getPathByID(String resID)
    {
        String filePath = InternetResourceCache.getCacheDir() + "/" + resID;
        return filePath;
    }

    public static byte[] getResByID(String resID)
    {
        try
        {
            String filePath = InternetResourceCache.getCacheDir() + "/" + resID;
            return readFileBytes(filePath);
        }
        catch (Exception e)
        {}
        return null;
    }

    public static boolean exists(String path)
    {
        File file = new File(path);
        if (file.exists())
            return true;
        return false;
    }
}
